package com.sixmac.controller;

import com.google.common.base.Strings;
import com.sixmac.annotation.AuthUser;
import com.sixmac.common.base.BaseController;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.ClienUser;
import com.sixmac.model.CourseChapter;
import com.sixmac.model.CourseComment;
import com.sixmac.pojo.SimulationPojo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by admin on 2018/8/13.
 */
@Controller
@ResponseBody
@RequestMapping("/api/course")
public class AddController extends BaseController {


    /**
     * @api {post} /api/course/addComment   0.1评论课程
     * @apiName add.addComment
     * @apiGroup add
     * @apiParam {String}  token  token
     * @apiParam {String}  courseId  课程id
     * @apiParam {String} userId 用户id
     * @apiParam {String} content 用户评论内容
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/addComment")
    public AjaxResult addComment(ClienUser user, Integer courseId, String content) {
        CourseComment courseComment = new CourseComment();
        courseComment.setContent(content);
        courseComment.setUserId(user.getId());
        courseComment.setCourseId(courseId);
        courseComment.setCreateDate(new Date());
        boolean f = Blade.create(CourseComment.class).save(courseComment);
        if (f) {
            return success("保存成功");
        }
        return error("保存失败");
    }

    /**
     * @api {post} /api/course/showComment   0.2显示课程评论
     * @apiName add.showComment
     * @apiGroup add
     * @apiParam {String}  courseId  课程id
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiSuccess {String} data.rows.content 评论内容
     * @apiSuccess {String} data.rows.createtime 创建时间
     * @apiSuccess {String} data.rows.name 评论名字
     * @apiSuccess {String} data.rows.headimg 头像
     * @apiError {Integer} 1
     */
    @RequestMapping("/showComment")
    public AjaxResult showComment(Integer courseId, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer size) {
        System.out.print("meizxiaomiu");
        BladePage<Map> bladePage = Db.paginate("select c.*,u.headimg,u.nickname from t_course_comment c inner join t_user u on u.id = c.userId where c.courseId=#{courseId}", getData("courseId", courseId), page, size);
        return json(bladePage);
    }

    /**
     * @api {post} /api/course/fine   0.3精品课程
     * @apiName add.fine
     * @apiGroup add
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiParam {String}  name  搜索名称
     * @apiSuccess {String} data.rows.id 课程id
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.playnum 播放量
     * @apiSuccess {String} data.rows.point 学习要点&考点(富文本)
     * @apiSuccess {String} data.rows.c 学习要点&考点
     * @apiSuccess {String} data.rows.firstUrl 简介视频
     * @apiError {Integer} 1
     */
    @RequestMapping("/fine")
    public AjaxResult showFine(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer size, String name) {
        StringBuilder sb = new StringBuilder();
        sb.append("select id,name,(select m.url from t_course_chapter c inner join t_media m on m.id = c.url  where c.url is not null and c.url != 0  and c.courseId = a.id order by c.sort limit 0,1)url,content as point,image,''firstUrl,pid,ifnull(playnum,0)playnum,createtime,updatetime,level from t_course_chapter a where pid = 0 and isFine = 1  ");
        this.getSql(sb, name);
        sb.append("order by createtime desc");
        BladePage<Map> mapBlade = Db.paginate(sb.toString(), null, page, size);
        this.ignore(mapBlade);
        return json(mapBlade);
    }

    /**
     * @api {post} /api/course/hot   0.4热门课程
     * @apiName add.hot
     * @apiGroup add
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiParam {String}  name  搜索名称
     * @apiSuccess {String} data.rows.id 课程id
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.playnum 播放量
     * @apiSuccess {String} data.rows.point 学习要点&考点(富文本)
     * @apiSuccess {String} data.rows.c 学习要点&考点
     * @apiSuccess {String} data.rows.firstUrl 简介视频
     * @apiError {Integer} 1
     */
    @RequestMapping("/hot")
    public AjaxResult showHot(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer size, String name) {
        StringBuilder sb = new StringBuilder();
        sb.append("select id,name,content as point,(select m.url from t_course_chapter c inner join t_media m on m.id = c.url  where c.url is not null and c.url != 0  and c.courseId = a.id order by c.sort limit 0,1)url,image,'' as firstUrl,pid,ifnull(playnum,0)playnum,createtime,updatetime,level from t_course_chapter a  where pid = 0 and isHot = 1  ");
        this.getSql(sb, name);
        sb.append("order by createtime desc");
        BladePage<Map> mapBlad1e = Db.paginate(sb.toString(), null, page, size);
        this.ignore(mapBlad1e);
        return json(mapBlad1e);
    }

    /**
     * @api {post} /api/course/showIndex   0.5通过分类显示课程
     * @apiName add.showIndex
     * @apiGroup add
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiParam {String}  categoryId  分类id
     * @apiParam {String}  name  搜索名称
     * @apiSuccess {String} data.rows.id 课程id
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.num 播放量
     * @apiSuccess {String} data.rows.point 学习要点&考点(富文本)
     * @apiSuccess {String} data.rows.c 学习要点&考点
     * @apiError {Integer} 1
     */
    @RequestMapping("/showIndex")
    public AjaxResult showIndexByCategory(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer size, String categoryId, String name) {
        StringBuilder sb = new StringBuilder();
        sb.append("select id,name,content as point,image,url,pid,ifnull(playnum,0)playnum,createtime,updatetime,level from t_course_chapter where pid = 0  ");
        if (!Strings.isNullOrEmpty(categoryId)) {
            sb.append("and categoryIds like ").append("'%<").append(categoryId).append(">%' ");
        }
        this.getSql(sb, name);
        sb.append("order by createtime desc");
        BladePage<Map> mapBlade = Db.paginate(sb.toString(), getData("categoryId", categoryId), page, size);
        this.ignore(mapBlade);
        return json(mapBlade);
    }

    /**
     * @api {post} /api/course/showCategory   0.6显示分类
     * @apiName add.showCategory
     * @apiGroup add
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiSuccess {String} data.rows.id 分类id
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.name 名称
     * @apiError {Integer} 1
     */
    @RequestMapping("/showCategory")
    public AjaxResult showCategory(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "4") Integer size) {
        StringBuilder sb = new StringBuilder();
        sb.append("select * from t_category");
        return json(Db.paginate(sb.toString(), null, page, size));
    }

    /**
     * @api {post} /api/course/simulation   0.7训练
     * @apiName add.simulation
     * @apiGroup add
     * @apiParam {String}  courseId  课程id
     * @apiSuccess {String} data.rows.title父级标题
     * @apiSuccess {String} data.rows.name 子级标题
     * @apiSuccess {String} data.rows.url 地址
     * @apiError {Integer} 1
     */
    @RequestMapping("/simulation")
    public AjaxResult getSimulation(Integer courseId) {
        if (courseId == null) {
            return error("课程找不到");
        }
        List<CourseChapter> courseChapterList = Blade.create(CourseChapter.class).findBy("courseId=#{courseId} and simulation is not null order by sort ", getData("courseId", courseId));
        List<CourseChapter> total = Blade.create(CourseChapter.class).findBy("courseId=#{courseId}", getData("courseId", courseId));

        List<SimulationPojo> simulationPojoList = new ArrayList<>();
        HashSet<String> set = new HashSet<>();
        for (CourseChapter courseChapter : courseChapterList) {
            CourseChapter c = this.getCourseChapterById(total, courseChapter.getPid());
            if (c != null) {
                if (set.contains(c.getName())) {
                    continue;
                }
                SimulationPojo pojo = new SimulationPojo();
                pojo.setTitle(c.getName());
                set.add(c.getName());
                List<Map> maps = new ArrayList<>();
                for (CourseChapter c1 : this.getCourseChapterByPid(total, courseChapter.getPid())) {
                    Map map = new HashMap();
                    map.put("name", c1.getName());
                    map.put("url", c1.getSimulation());
                    maps.add(map);
                }
                pojo.setList(maps);
                simulationPojoList.add(pojo);
            }
        }
        return json(getData("list", simulationPojoList));

    }


    private CourseChapter getCourseChapterById(List<CourseChapter> courseChapterList, Integer id) {
        for (CourseChapter c : courseChapterList) {
            if (c.getId().compareTo(id) == 0)
                return c;
        }
        return null;
    }

    private List<CourseChapter> getCourseChapterByPid(List<CourseChapter> courseChapterList, Integer pid) {
        List<CourseChapter> list = new ArrayList<>();
        for (CourseChapter c : courseChapterList) {
            if (c.getPid().compareTo(pid) == 0)
                list.add(c);
        }
        return list;
    }


    private StringBuilder getSql(StringBuilder sb, String name) {
        if (!Strings.isNullOrEmpty(name)) {
            sb.append(" and name  like '%" + name + "%'");
        }
        return sb;
    }

    private void ignore(BladePage<Map> bladePage) {
        for (Map mm : bladePage.getRows()) {
            String content = Convert.toStr(mm.get("point"));
            if (!Strings.isNullOrEmpty(content)) {

                mm.put("c", content.replaceAll("[^\\u4e00-\\u9fa5,，。.0-9()]", ""));
            } else {
                mm.put("c", "暂无课程要点");
            }
        }

    }


}
